package com.jeeplus.test.jlnu.admissionInfo.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.listener.ReadListener;
import com.jeeplus.test.jlnu.admissionInfo.domain.entity.AdmissionInfo;
import com.jeeplus.test.jlnu.admissionInfo.domain.entity.StudentsOffice;
import com.jeeplus.test.jlnu.admissionInfo.service.AdmissionExcelService;
import com.jeeplus.test.jlnu.admissionInfo.service.StudentsOfficeService;

import java.util.ArrayList;
import java.util.List;

public class StudentsOfficeDataListener extends AnalysisEventListener<StudentsOffice> {
    private final StudentsOfficeService excelServiceStu;

    private final ProgressCallback progressCallback;
    private static final int BATCH_COUNT = 500;
    private final String officeId;

    private List<StudentsOffice> dataList = new ArrayList<>();
    private int totalRecords;
    private int currentRecords;



    public StudentsOfficeDataListener(StudentsOfficeService excelServiceStu,StudentsOfficeDataListener.ProgressCallback progressCallback, int totalRecords,String officeId) {
        this.excelServiceStu = excelServiceStu;
        this.progressCallback = progressCallback;
        this.totalRecords = totalRecords;
        this.officeId = officeId;
    }

    @Override
    public void invoke(StudentsOffice studentsOffice, AnalysisContext analysisContext) {
        // 获取当前行号
        int currentRow = analysisContext.readRowHolder().getRowIndex();

        // 判断当前是否是第二行，跳过第二行
        if (currentRow == 1) {
            return; // 跳过第二行
        }
        studentsOffice.setOfficeId(officeId);
        dataList.add(studentsOffice);
        currentRecords++;

        if (dataList.size() >= BATCH_COUNT) {
            saveDataToDatabase();
            dataList.clear();
        }

        updateProgress();
    }



    private void saveDataToDatabase() {
        if (!dataList.isEmpty()) {
            excelServiceStu.insertDataAdmission(dataList);
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (!dataList.isEmpty()) {
            saveDataToDatabase();
            dataList.clear();
        }
        updateProgress();
    }
    private void updateProgress() {
        int progress = (int) (((double) currentRecords / totalRecords) * 100);
        progressCallback.onProgress(progress);
    }

    public interface ProgressCallback {
        void onProgress(int progress);
    }
}
